package fmt_e

import (
	"fmt"
	"strings"
)

const (
	bgn = `func (e %s) String() string {
	switch e {
`
	mid = `	case %s:
		return %q
`
	dft = `	return fmt.Sprintf("%s_unknow(%%d)", e)
`
	end = `}
`
	vrf = `func (e %s) Verify() bool {
	if e <= 0 || e >= %s_Max {
		return false
	}
	return true
}
`

	bgn_ = `func (e *%s) Parse(s string) error {
	switch s {
`
	mid_ = `	case %q:
		*e = %s
`
	dft_ = `	return fmt.Errorf("%s_incorrect(%%s)", s)
`

	field_ = `	%-20s %-10s = %d; // %s
`
)

// ---------- for go enum
type EnumUnit struct {
	name    string // enum name
	prefix  string // 前缀
	adding  bool   //
	infun   bool
	members []string
} //
func (this *EnumUnit) addMember(m string) {
	if this.prefix == "" {
		this.prefix = strings.Split(m, "_")[0]
	}
	if strings.ToUpper(m) == strings.ToUpper(this.prefix+"_MAX") {
		return
	}
	this.members = append(this.members, m)
}
func (this *EnumUnit) fmtstr(toCase ...bool) string {

	str := fmt.Sprintf(bgn, this.name)
	for n, _ := range this.members {
		s := strings.TrimPrefix(this.members[n], this.prefix+"_")
		if len(toCase) > 0 && toCase[0] {
			s = Camel2Case(s)
		}
		str += fmt.Sprintf(mid, this.members[n], s)
	}
	str += `	}
`
	str += fmt.Sprintf(dft, this.prefix)
	return str + end
}
func (this *EnumUnit) vrfstr() string {
	return fmt.Sprintf(vrf, this.name, this.prefix)
}
func (this *EnumUnit) parstr() string {
	str := fmt.Sprintf(bgn_, this.name)
	for n, _ := range this.members {
		str += fmt.Sprintf(mid_, strings.TrimPrefix(this.members[n], this.prefix+"_"), this.members[n])
	}
	str += `	}
`
	str += fmt.Sprintf(dft_, this.prefix)
	return str + end
}

//------------------------------------------------------------------------------

// 驼峰式写法转为下划线写法
func Camel2Case(s string) string {
	data := make([]byte, 0, len(s)*2)
	j := false
	num := len(s)
	for i := 0; i < num; i++ {
		d := s[i]
		if i > 0 && d >= 'A' && d <= 'Z' && j {
			data = append(data, '_')
		}
		if d != '_' {
			j = true
		}
		data = append(data, d)
	}
	return strings.ToLower(string(data[:]))
}

// 下划线写法转为驼峰写法
func Case2Camel(name string) string {
	name = strings.Replace(name, "_", " ", -1)
	name = strings.Title(name)
	return strings.Replace(name, " ", "", -1)
}
